package com.sctvcloud.zhaohua_sd.ui.dialog;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;

import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.dialog.BaseDialogFragment;
import com.ruihang.generalibrary.ui.dialog.AlertDialogFragment;
import com.sctvcloud.zhaohua_sd.R;
import com.sctvcloud.zhaohua_sd.base.BaseActivity;
import com.sctvcloud.zhaohua_sd.beans.FVersionInfo;
import com.sctvcloud.zhaohua_sd.http.AbsNetCallBack;
import com.sctvcloud.zhaohua_sd.http.NetUtils;
import com.sctvcloud.zhaohua_sd.ui.utils.update.DownloadManager;
import com.sctvcloud.zhaohua_sd.utils.VersionUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/4/24 0024.
 */

public class CheckPermission implements AlertDialogFragment.OnViewClick {

    public static final int SETTING_REQUEST = 110;
    public static final int WHAT_FINISH = 210;

    private final String TAG_F_SETTING = "tag_f_setting";

    private BaseActivity activity;
    DownloadManager manager = null;
    private Dialog updateDialog = null;
    /**
     * 是否有存储权限
     */
    private boolean hasSDVersion;
    private boolean requestPersimissoning;
    private boolean isUpdate = false;
    private boolean isForce = false;
    /**
     * 是否正在获取版本信息
     */
    private boolean isGettingVersionInfo;
    /**
     * 是否已经获取了版本信息
     */
    private boolean hasGettedVersion;
    private boolean hasEnoughPermisson;
    public int show_type;//如果是最新版本，show_type为1，则在SettingsActivity显示toast

    private AlertDialogFragment alertDialogFragment;
    private boolean isAlertPosiCalled;

    private Object saveInstanceSync = new Object();
    private boolean isSaveInstanceCalled;
    private String msgTemp;
    private DownloadManager.OnDownloadSuccess downloadListener;

    public CheckPermission(BaseActivity activity) {
        this.activity = activity;
    }

    public void updateVersion2(DownloadManager.OnDownloadSuccess downloadListener) {
        this.downloadListener = downloadListener;
        getVersion();
    }

    public void updateVersion() {
        hasEnoughPermisson = checkPersimissons();
        if (hasEnoughPermisson) {
            if (NotificationManagerCompat.from(activity).areNotificationsEnabled()) {
                getVersion();
            } else {
                synchronized (saveInstanceSync) {
                    if (isSaveInstanceCalled) {
                        msgTemp = "本app需要获取到\"通知\"权限才能提供服务";
                    } else {
                        showToastFragment("本app需要获取到\"通知\"权限才能提供服务", 2);
                    }
                }
            }
        } else {
            requestPersimissoning = true;
        }
    }

    /**
     * @param lis
     * @param permissionName
     * @return 是否需要打开设置界面
     */
    private boolean checkPersimisson(List<String> lis, String permissionName) {
        int per = ContextCompat.checkSelfPermission(activity, permissionName);
        if (per != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permissionName)) {
                lis.add(permissionName);
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    private boolean checkPersimissons() {

        List<String> lis = new ArrayList<>();
        boolean hasShouldSetting = false;
        StringBuffer sb = new StringBuffer();
        sb.append(activity.getString(R.string.should_get_permission_msg) + "\n\n");
        boolean b = checkPersimisson(lis, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (b) {
            sb.append("SD卡读取权限\n");
            hasShouldSetting = true;
        } else {
            hasSDVersion = lis.size() == 0;
        }
//        b = checkPersimisson(lis, Manifest.permission.ACCESS_FINE_LOCATION);
//        b = b & checkPersimisson(lis, Manifest.permission.ACCESS_COARSE_LOCATION);
//        if (b) {
//            sb.append("位置权限                           \n");
//            hasShouldSetting = true;
//        }
        if (lis.size() > 0) {
            ActivityCompat.requestPermissions(activity, lis.toArray(new String[lis.size()]), DownloadManager.PERMISSION_REQUEST);
            return false;
        } else if (hasShouldSetting) {
            if (!NotificationManagerCompat.from(activity).areNotificationsEnabled()) {
                sb.append("通知权限             \n");
            }
            synchronized (saveInstanceSync) {
                if (isSaveInstanceCalled) {
                    msgTemp = sb.toString();
                } else {
                    showToastFragment(sb.toString(), 0);
                }
            }
            return false;
        } else {
            return true;
        }
    }

    private void showToastFragment(String msg, int mode) {
        // if (alertDialogFragment == null) {
        alertDialogFragment = new AlertDialogFragment().setOkStrRes(R.string.go_setting)
                .setCancleStrRes(R.string.soft_update_exit).setMsgGravity(Gravity.LEFT)
                .setOnViewClick(this).setCancelOut(false);
        alertDialogFragment.setCallBackS(new BaseDialogFragment.ICallBack() {
            @Override
            public void onCallBackMsg(BaseDialogFragment fragment, Message msg) {
                if (isAlertPosiCalled) {
                    isAlertPosiCalled = false;
                } else {
                    JLog.e("will exit");
                    System.exit(0);
                }
            }
        });
        //}
        alertDialogFragment.setMsgStr(msg);
        alertDialogFragment.setModeTag(mode);
        if (alertDialogFragment.isResumed()) {
            return;
        } else {
            alertDialogFragment.show(activity.getSupportFragmentManager(), TAG_F_SETTING);
        }
    }

    private void toSetting(boolean isNotice) {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS
                , Uri.parse("package:" + activity.getPackageName()));
        activity.startActivityForResult(intent, SETTING_REQUEST);
    }

    public void onSaveInstance() {
        synchronized (saveInstanceSync) {
            isSaveInstanceCalled = true;
        }
    }

    public void onResume() {
        synchronized (saveInstanceSync) {
            isSaveInstanceCalled = false;
            if (!TextUtils.isEmpty(msgTemp)) {
                showToastFragment(msgTemp, 0);
                msgTemp = null;
            }
        }
    }

    public void onRestoreInstance() {
        synchronized (saveInstanceSync) {
            isSaveInstanceCalled = false;
            if (!TextUtils.isEmpty(msgTemp)) {
                showToastFragment(msgTemp, 0);
                msgTemp = null;
            }
        }
    }

    /**
     * 版本升级
     */
    private synchronized void getVersion() {
        if (isGettingVersionInfo) {
            return;
        }
        isGettingVersionInfo = true;
        NetUtils.getNetAdapter().getVersion(activity.getOwnerName(), "sctv/appVersion.json", new AbsNetCallBack<FVersionInfo>(FVersionInfo.class) {
            @Override
            public void onSuc(FVersionInfo fVersionInfo) {
                manager = new DownloadManager(activity, fVersionInfo);
                manager.notifyPermission(hasSDVersion);
                manager.setDownloadListener(downloadListener);
                manager.setAction(new DownloadManager.OnDialogAction() {

                    @Override
                    public void onPositiveButtonClick() {
                        hasEnoughPermisson = checkPersimissons();
                        if (hasEnoughPermisson) {
                            if (NotificationManagerCompat.from(activity).areNotificationsEnabled()) {
                                manager.notifyPermission(true);
                                manager.onUpdateAction(activity.getSupportFragmentManager());
                                isUpdate = true;
                            } else {
                                synchronized (saveInstanceSync) {
                                    if (isSaveInstanceCalled) {
                                        msgTemp = "本app需要获取到\"通知\"权限才能提供服务";
                                    } else {
                                        showToastFragment("本app需要获取到\"通知\"权限才能提供服务", 2);
                                    }
                                }
                            }
                        }

                    }

                    @Override
                    public void OnNegativeButtonClick() {
                        isUpdate = false;
//                        if (isForce) {
//                            activity.finish();
//                        } else {
                        onFinish();
//                        }
//                        toMain(true);

                    }

                    @Override
                    public void onUploadFailed() {
                        if (isForce) {
                            activity.finish();
                        } else {
                            onFinish();
                        }
                    }
                });
                // 检查软件更新
                if (updateDialog != null && updateDialog.isShowing()) {
                    updateDialog.dismiss();
                }
                isForce = fVersionInfo.isforce();
//                isForce = false;

                boolean b = manager.checkUpdate(VersionUtil.getVersionCode(activity),
                        fVersionInfo.getVersionCode(), isForce, fVersionInfo.getDescription(), activity.getSupportFragmentManager());
                if (!b) {
                    if (show_type == 1) {
                        activity.toast("已经更新到最新版本啦！");
                    }
                    onFinish();
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
                onFinish();
            }
        });
//
    }

    public void onActivityResult() {
//        updateVersion();
        if (manager != null && activity != null) {
            manager.showNoticeDialog(activity.getSupportFragmentManager());
        }
    }

    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == DownloadManager.PERMISSION_REQUEST) {
            StringBuffer sb = new StringBuffer();
            boolean shouldToSetting = false;
            sb.append(activity.getString(R.string.should_get_permission_msg) + "\n\n");
            for (int i = 0; i < permissions.length; i++) {
                if (Manifest.permission.WRITE_EXTERNAL_STORAGE.equals(permissions[i])) {
                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                        sb.append("SD卡存储权限           \n");
                        shouldToSetting = true;
                    } else {
                        hasSDVersion = true;
                    }
                } else if (Manifest.permission.ACCESS_FINE_LOCATION.equals(permissions[i])
                        || Manifest.permission.ACCESS_COARSE_LOCATION.equals(permissions[i])) {
                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                        sb.append("位置/定位权限           \n");
                        shouldToSetting = true;
                    }
                }
            }
            if (!NotificationManagerCompat.from(activity).areNotificationsEnabled()) {
                sb.append("通知权限             \n");
                shouldToSetting = true;
            }
            hasEnoughPermisson = !shouldToSetting;
            if (manager != null) {
                manager.notifyPermission(hasSDVersion);
            }
            if (hasEnoughPermisson) {
                requestPersimissoning = false;
                getVersion();
            } else {
                synchronized (saveInstanceSync) {
                    if (isSaveInstanceCalled) {
                        msgTemp = sb.toString();
                    } else {
                        showToastFragment(sb.toString(), 0);
                    }
                }
            }
        }
    }

    @Override
    public boolean onViewClick(View view, int viewItem, int mode) {
        if (viewItem == AlertDialogFragment.VIEW_ITEM_OK) {
            isAlertPosiCalled = true;
            toSetting(alertDialogFragment.getModeTag() == 2);
        }
        return true;
    }

    public boolean hasCheckFinish() {
        return hasEnoughPermisson && hasGettedVersion && (alertDialogFragment == null || !alertDialogFragment.isResumed())
                && (manager == null || manager.hasCheckUpdateFinish());
    }

    private void onFinish() {
        Message msg = Message.obtain();
        msg.what = WHAT_FINISH;
        activity.onOtherCallback(msg);
    }
}
